<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试详情 - 学生端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }

        .page-title {
            font-size: 2.5em;
            margin: 0;
            font-weight: 300;
        }

        .page-subtitle {
            font-size: 1.1em;
            margin: 10px 0 0 0;
            opacity: 0.9;
        }

        .exam-info-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .exam-info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .info-item {
            text-align: center;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .info-label {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 8px;
        }

        .info-value {
            font-size: 1.2em;
            font-weight: bold;
            color: var(--primary-color);
        }

        .result-summary {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            text-align: center;
        }

        .score-display {
            font-size: 4em;
            font-weight: bold;
            margin-bottom: 20px;
        }

        .score-excellent { color: #28a745; }
        .score-good { color: #17a2b8; }
        .score-average { color: #ffc107; }
        .score-poor { color: #dc3545; }

        .score-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }

        .score-item {
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            text-align: center;
        }

        .score-number {
            font-size: 2em;
            font-weight: bold;
            color: #28a745;
            margin-bottom: 10px;
        }

        .score-label {
            color: #666;
            font-size: 0.9em;
        }

        .questions-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .section-title {
            font-size: 1.5em;
            font-weight: bold;
            margin-bottom: 20px;
            color: var(--neutral-dark);
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 10px;
        }

        .question-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 4px solid var(--primary-color);
        }

        .question-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .question-number {
            font-size: 1.1em;
            font-weight: bold;
            color: var(--primary-color);
        }

        .question-result {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: bold;
        }

        .result-correct {
            background: #d4edda;
            color: #155724;
        }

        .result-incorrect {
            background: #f8d7da;
            color: #721c24;
        }

        .question-content {
            font-size: 1.1em;
            line-height: 1.6;
            margin-bottom: 15px;
            color: var(--neutral-dark);
        }

        .options-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .option-item {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 6px;
            border: 2px solid transparent;
            transition: all 0.3s ease;
        }

        .option-item.correct {
            background: #d4edda;
            border-color: #28a745;
        }

        .option-item.incorrect {
            background: #f8d7da;
            border-color: #dc3545;
        }

        .option-item.selected {
            background: #fff3cd;
            border-color: #ffc107;
        }

        .option-label {
            font-weight: bold;
            margin-right: 10px;
        }

        .option-text {
            color: var(--neutral-dark);
        }

        .explanation {
            margin-top: 15px;
            padding: 15px;
            background: #e3f2fd;
            border-radius: 6px;
            border-left: 4px solid #2196f3;
        }

        .explanation-title {
            font-weight: bold;
            color: #1976d2;
            margin-bottom: 8px;
        }

        .explanation-content {
            color: #424242;
            line-height: 1.5;
        }

        .actions-section {
            text-align: center;
            margin-top: 30px;
        }

        .btn {
            padding: 12px 24px;
            margin: 0 10px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background: #1e5f7a;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #545b62;
            transform: translateY(-2px);
        }

        .loading-state {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .error-state {
            text-align: center;
            padding: 40px;
            color: #dc3545;
        }

        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }

            .page-title {
                font-size: 2em;
            }

            .exam-info-grid {
                grid-template-columns: 1fr;
            }

            .score-details {
                grid-template-columns: repeat(2, 1fr);
            }

            .question-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1 class="page-title">📊 考试详情</h1>
            <p class="page-subtitle">查看您的考试结果和答题详情</p>
        </div>

        <!-- 加载状态 -->
        <div id="loadingState" class="loading-state">
            <div class="loading-pulse" style="margin-bottom: 16px;"></div>
            <p>正在加载考试详情...</p>
        </div>

        <!-- 错误状态 -->
        <div id="errorState" class="error-state" style="display: none;">
            <h3>❌ 加载失败</h3>
            <p id="errorMessage">无法加载考试详情，请稍后重试</p>
            <button class="btn btn-primary" onclick="location.reload()">重新加载</button>
        </div>

        <!-- 考试详情内容 -->
        <div id="examDetailContent" style="display: none;">
            <!-- 考试基本信息 -->
            <div class="exam-info-card">
                <h2 class="section-title">📋 考试信息</h2>
                <div class="exam-info-grid">
                    <div class="info-item">
                        <div class="info-label">考试名称</div>
                        <div class="info-value" id="examTitle">-</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">考试时间</div>
                        <div class="info-value" id="examTime">-</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">答题时长</div>
                        <div class="info-value" id="examDuration">-</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">题目总数</div>
                        <div class="info-value" id="totalQuestions">-</div>
                    </div>
                </div>
            </div>

            <!-- 成绩汇总 -->
            <div class="result-summary">
                <div class="score-display" id="scoreDisplay">-</div>
                <h3>您的成绩</h3>
                <div class="score-details">
                    <div class="score-item">
                        <div class="score-number" id="correctCount">-</div>
                        <div class="score-label">正确题数</div>
                    </div>
                    <div class="score-item">
                        <div class="score-number" id="incorrectCount">-</div>
                        <div class="score-label">错误题数</div>
                    </div>
                    <div class="score-item">
                        <div class="score-number" id="accuracyRate">-</div>
                        <div class="score-label">正确率</div>
                    </div>
                </div>
            </div>

            <!-- 题目详情 -->
            <div class="questions-section">
                <h2 class="section-title">📝 答题详情</h2>
                <div id="questionsList">
                    <!-- 题目列表将在这里动态生成 -->
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="actions-section">
                <button class="btn btn-primary" onclick="goToExamList()">返回考试列表</button>
                <button class="btn btn-secondary" onclick="goToExamRecords()">查看所有记录</button>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let examDetail = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadExamDetail();
        });

        // 检查用户认证
        function checkAuth() {
            if (!UserManager.isLoggedIn()) {
                Message.error('请先登录');
                window.location.href = '../login.html';
                return;
            }
        }

        // 加载考试详情
        async function loadExamDetail() {
            try {
                // 首先尝试从sessionStorage获取考试详情数据
                const detailData = sessionStorage.getItem('examDetail');
                if (detailData) {
                    examDetail = JSON.parse(detailData);
                    renderExamDetail();
                    return;
                }

                // 如果没有sessionStorage数据，尝试从URL参数获取examId
                const urlParams = new URLSearchParams(window.location.search);
                const examId = urlParams.get('examId');
                if (examId) {
                    await loadExamDetailFromAPI(examId);
                    return;
                }

                // 如果都没有，显示错误
                showError('没有找到考试详情数据，请从考试记录页面重新进入');
                
            } catch (error) {
                console.error('加载考试详情失败:', error);
                showError('加载考试详情失败，请稍后重试');
            }
        }

        // 从API加载考试详情
        async function loadExamDetailFromAPI(examId) {
            try {
                const response = await API.get(`/exam/answer-detail/${examId}`);
                if (response.success) {
                    examDetail = {
                        exam: response.exam,
                        record: response.record,
                        answers: response.answers,
                        examRecord: response.record
                    };
                    renderExamDetail();
                } else {
                    showError(response.message || '获取考试详情失败');
                }
            } catch (error) {
                console.error('从API加载考试详情失败:', error);
                showError('获取考试详情失败，请稍后重试');
            }
        }

        // 渲染考试详情
        function renderExamDetail() {
            if (!examDetail) return;

            const { exam, record, answers, examRecord } = examDetail;
            
            // 隐藏加载状态，显示内容
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('examDetailContent').style.display = 'block';

            // 渲染考试基本信息
            document.getElementById('examTitle').textContent = exam.title || '未知考试';
            document.getElementById('examTime').textContent = formatDate(record.examTime);
            document.getElementById('examDuration').textContent = formatDuration(exam.timeLimit || 0);
            document.getElementById('totalQuestions').textContent = record.totalQuestions || 0;

            // 渲染成绩汇总
            const correctCount = record.score || 0;
            const totalCount = record.totalQuestions || 0;
            const incorrectCount = totalCount - correctCount;
            const accuracyRate = totalCount > 0 ? Math.round((correctCount / totalCount) * 100) : 0;

            document.getElementById('correctCount').textContent = correctCount;
            document.getElementById('incorrectCount').textContent = incorrectCount;
            document.getElementById('accuracyRate').textContent = accuracyRate + '%';

            // 渲染总分显示
            const scoreDisplay = document.getElementById('scoreDisplay');
            scoreDisplay.textContent = `${correctCount}/${totalCount}`;
            scoreDisplay.className = 'score-display ' + getScoreClass(accuracyRate);

            // 渲染题目详情
            renderQuestions(answers || []);
        }

        // 渲染题目列表
        function renderQuestions(answers) {
            const questionsList = document.getElementById('questionsList');
            
            if (!answers || answers.length === 0) {
                questionsList.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">暂无题目详情</p>';
                return;
            }

            questionsList.innerHTML = answers.map((answer, index) => {
                const isCorrect = answer.isCorrect;
                const resultClass = isCorrect ? 'result-correct' : 'result-incorrect';
                const resultText = isCorrect ? '正确' : '错误';

                return `
                    <div class="question-card">
                        <div class="question-header">
                            <div class="question-number">第 ${index + 1} 题</div>
                            <div class="question-result ${resultClass}">${resultText}</div>
                        </div>
                        <div class="question-content">${answer.questionContent || '题目内容'}</div>
                        <ul class="options-list">
                            ${renderOptions(answer)}
                        </ul>
                        ${answer.explanation ? `
                            <div class="explanation">
                                <div class="explanation-title">💡 解析</div>
                                <div class="explanation-content">${answer.explanation}</div>
                            </div>
                        ` : ''}
                    </div>
                `;
            }).join('');
        }

        // 渲染选项
        function renderOptions(answer) {
            const options = [
                { key: 'A', value: answer.optionA },
                { key: 'B', value: answer.optionB },
                { key: 'C', value: answer.optionC },
                { key: 'D', value: answer.optionD }
            ].filter(opt => opt.value);

            return options.map(option => {
                const isCorrect = option.key === answer.correctAnswer;
                const isSelected = option.key === answer.studentAnswer;
                let optionClass = 'option-item';
                
                if (isCorrect) optionClass += ' correct';
                if (isSelected && !isCorrect) optionClass += ' incorrect';
                if (isSelected) optionClass += ' selected';

                return `
                    <li class="${optionClass}">
                        <span class="option-label">${option.key}.</span>
                        <span class="option-text">${option.value}</span>
                    </li>
                `;
            }).join('');
        }

        // 获取成绩等级样式
        function getScoreClass(percentage) {
            if (percentage >= 90) return 'score-excellent';
            if (percentage >= 80) return 'score-good';
            if (percentage >= 60) return 'score-average';
            return 'score-poor';
        }

        // 显示错误状态
        function showError(message) {
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('errorMessage').textContent = message;
            document.getElementById('errorState').style.display = 'block';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 格式化时长
        function formatDuration(minutes) {
            if (!minutes) return '0分钟';
            const hours = Math.floor(minutes / 60);
            const mins = minutes % 60;
            if (hours > 0) {
                return `${hours}小时${mins}分钟`;
            }
            return `${mins}分钟`;
        }

        // 返回考试列表
        function goToExamList() {
            window.location.href = 'exams.html';
        }

        // 返回考试记录
        function goToExamRecords() {
            window.location.href = 'exam-records.html';
        }
    </script>
</body>
</html>
